package org.wangzs.blog.util;

import java.io.IOException;

import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

public class PageTag extends TagSupport {

	private static final long serialVersionUID = 1L;
	
	private String baseUrl;
	private int pageSize;
	private int pageNum;
	private int totalNum;
	
	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public int getPageNum() {
		return pageNum;
	}

	public void setPageNum(int pageNum) {
		this.pageNum = pageNum;
	}

	public int getTotalNum() {
		return totalNum;
	}

	public void setTotalNum(int totalNum) {
		this.totalNum = totalNum;
	}

	public String getBaseUrl() {
		return baseUrl;
	}

	public void setBaseUrl(String baseUrl) {
		this.baseUrl = baseUrl;
	}

	@Override
	public int doStartTag() {
		StringBuffer pager = new StringBuffer();
		pager.append("<ul class='pagination'>");
		
		int totalPage = (int) Math.ceil((double)totalNum/pageSize);
		
		//pre page
		if(1 == pageNum){
			pager.append("<li class='disabled'><a>&laquo;</a></li>");
		}else{
			pager.append("<li><a href='"+baseUrl+(pageNum-1)+"'>&laquo;</a></li>");
		}
		
		int left = pageNum-5>0?(pageNum-5):1;
		for(int i=left;i<pageNum;i++){
			pager.append("<li><a href='"+baseUrl+i+"'>"+i+"</a></li>");
		}
		
		pager.append("<li class='active'><a href='"+baseUrl+pageNum+"'>"+pageNum+"</a></li>");
		
		int right = totalPage-pageNum>5?5:totalPage;
		for(int i=pageNum+1;i<=right;i++){
			pager.append("<li><a href='"+baseUrl+i+"'>"+i+"</a></li>");
		}
		
		//post page
		if(totalPage == pageNum){
			pager.append("<li class='disabled'><a>&raquo;</a></li>");
		}else{
			pager.append("<li><a href='"+baseUrl+(pageNum+1)+"'>&raquo;</a></li>");
		}
		
		pager.append("</ul>");
		
		JspWriter out = pageContext.getOut();
		try {
			out.println(pager.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return SKIP_BODY;
	}
	
}
